package com.edu.nchu.study.pattern;

import java.util.Observable;
import java.util.Observer;

/**
 * 观察者模式
 *  Jdk9开始废弃Observable&Observer
 */
public class ObservorPattern {

    public static void main(String[] args) {
        News news = new News();
        news.addObserver(new School());
        news.addObserver(new Company());

        news.setNews("周杰伦奶茶开卖了...........");
        news.setNews("周杰伦和他的奶茶开卖了...........");
        // 线程异步通知
        Thread thread = new Thread() {
            @Override
            public void run() {
                news.publishNews();
            }
        };
        thread.start();
        System.out.println("make news and publish completed!!!");
    }


    /**
     * 新闻对象
     */
    public static class News extends Observable {

        private String news;


        public void publishNews() {
            System.out.println("this is news, start publish news");
            notifyObservers(news);
            System.out.println("this is news, completed publish news");

        }

        public void setNews(String news) {
            this.news = news;
            setChanged();
        }
    }

    /**
     * 学校订阅者
     */
    public static class School implements Observer {
        @Override
        public void update(Observable o, Object arg) {
            System.out.println("this is school observer, receive news" + arg);
        }
    }

    /**
     * 学校订阅者
     */
    public static class Company implements Observer {
        @Override
        public void update(Observable o, Object arg) {
            System.out.println("this is company observer, receive news" + arg);
        }
    }




}
